package com.ping.common;

import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.jfinal.plugin.activerecord.Record;

public class Json {
	public static JSONArray ListToJsonArray(List<Record> records) throws JSONException{
		Iterator<Record> iterator = records.listIterator();
		JSONArray array = new JSONArray();
		
		if (records.size() != 0) {
			String[] names = records.get(0).getcolumnNames();

			while (iterator.hasNext()) {
				Record record = iterator.next();

				JSONObject object = new JSONObject();
				for (int i = 0; i < names.length; i++) {
					object.put(names[i], record.get(names[i], null));
				}

				array.put(object);
			}
		}
		return array;
	}
	
	public static JSONObject recordToJsonObject(Record record) throws JSONException{
		String[] names = record.getcolumnNames();
		JSONObject object = new JSONObject();
		
		for (int i = 0; i < names.length; i++) {
			object.put(names[i], record.get(names[i], null));
		}
		
		return object;
	}

}
